package com.kming.crypto.annotation;

import com.kming.crypto.DecryptRequestBody;
import com.kming.crypto.EncryptResponseBody;
import com.kming.crypto.config.CryptoConfig;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;

/**
 * 注解在启动类上时开启接口加解密
 * 2022/5/13 9:29
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import({CryptoConfig.class, EnableControllerCrypto.ImportSelect.class})
public @interface EnableControllerCrypto {
    /**
     * 请求解密控制器
     */
    @SuppressWarnings("unused")
    Class<? extends RequestBodyAdvice> requestAdvice() default DecryptRequestBody.class;

    /**
     * 返回数据加密控制器
     */
    @SuppressWarnings("unused")
    Class<? extends ResponseBodyAdvice> responseAdvice() default EncryptResponseBody.class;

    class ImportSelect implements ImportSelector{

        @SuppressWarnings({"rawtypes","ConstantConditions"}) //忽略未指定类型、空指针警告
        @Override
        public String[] selectImports(AnnotationMetadata importingClassMetadata) {
            Map<String, Object> map = importingClassMetadata
                    .getAnnotationAttributes(EnableControllerCrypto.class.getName());
            String[] classNames = new String[2];
            classNames[0] = ((Class)map.get("requestAdvice")).getName();
            classNames[1] = ((Class)map.get("responseAdvice")).getName();
            return classNames;
        }
    }
}
